<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { templateAPI } from '@/services/api'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useCurveStore } from '@/stores/curveStore'

const router = useRouter()
const curveStore = useCurveStore()
const templates = ref([])
const loading = ref(false)

// 获取模板列表
const fetchTemplates = async () => {
  loading.value = true
  try {
    const response = await templateAPI.getAll()
    templates.value = response.data
  } catch (error) {
    console.error('获取模板列表失败:', error)
    ElMessage.error('获取模板列表失败')
  } finally {
    loading.value = false
  }
}

// 应用模板
const handleApply = (template) => {
  curveStore.applyTemplate(template.settings)
  router.push({
    name: 'curve',
    params: { 
      settings: 'template'
    }
  })
}

// 删除模板
const handleDelete = async (template) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个模板吗？',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    await templateAPI.delete(template.id)
    ElMessage.success('删除成功')
    fetchTemplates() // 重新加载列表
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除模板失败:', error)
      ElMessage.error('删除模板失败')
    }
  }
}

onMounted(() => {
  fetchTemplates()
})
</script>

<template>
  <div class="template-view">
    <el-table :data="templates" v-loading="loading" border>
      <el-table-column 
        type="index" 
        label="序号" 
        width="80" 
        align="center"
      >
        <template #default="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="name" label="模板名称" />
      <el-table-column prop="author" label="作者" />
      <el-table-column prop="note" label="备注" />
      <el-table-column prop="create_time" label="创建时间" />
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <div class="operation-buttons">
            <el-button type="primary" @click="handleApply(row)">
              应用
            </el-button>
            <el-button type="danger" @click="handleDelete(row)">
              删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<style scoped>
.template-view {
  padding: 20px;
}

.operation-buttons {
  display: flex;
  gap: 12px;
  justify-content: center;
}
</style>